package one.coder.netty.chapter.thirteen;

import one.coder.netty.chapter.common.model.Command;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * 对象传递，客户端代码
 * 
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
public class LongWaitObjectClientHandler extends SimpleChannelHandler {
	
	private static int count = 0;

	/**
	 * 当绑定到服务端的时候触发，给服务端发消息。
	 * 
	 * @author lihzh
	 * @alia OneCoder
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx,
			final ChannelStateEvent e) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 向服务端发送Object信息
				sendObject(e.getChannel());

			}
		}).start();
	}

	/**
	 * 发送Object
	 * 
	 * @param channel
	 * @author lihzh
	 * @alia OneCoder
	 */
	private void sendObject(Channel channel) {
		for (;;) {
			count++;
			Command command = new Command();
			command.setActionName("Hello action.");
			// Command commandOne = new Command();
			// commandOne.setActionName("Hello action. One");
			// Command command2 = new Command();
			// command2.setActionName("Hello action. Two");
			// channel.write(command2);
			channel.write(command);
			System.out.println("Write: " + count);
			// channel.write(commandOne);
			// channel.disconnect();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 */
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		System.out.println("Exception: " + e.getCause());
	}

}
